from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosDining, collectionDiningList, collectionStallDeviceList
from app.db.dbDiningQuery import queryDiningName 
from app.globals.publicMethod import globalTimeToString

def queryAllStall(diningNo):
    '''
    查询指定餐厅的所有档口
    '''
    try:
        for id in diningNo:
            cond = {'diningNo': id}
            mg_client = get_mongo_client()
            res = mg_client[dbSynPosDining][collectionDiningList].find_one(cond)
            if res is None:
                return False

            diningList = []
            tempres = res.get('stallList')
            if tempres is None:
                return diningList

            for v in tempres:
                users = {
                    'diningNo': id,
                    'diningName': res['diningName'],
                    'stallNo': v.get('stallNo'),
                    'stallName': v.get('stallName'),
                    'createTime': globalTimeToString(v.get('createTime')),
                    'updateTime': globalTimeToString(v.get('updateTime')),
                    'creatorUserName': v.get('creatorUserName'),
                    'editorUserName': v.get('editorUserName'),
                    'stallDesc': v.get('stallDesc')
                }
                diningList.append(users)   

        return diningList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryStall(diningNo, RelationStallNo):
    '''
    查询指定餐厅的指定档口
    '''
    stallList = []
    if RelationStallNo is None or len(RelationStallNo) <= 0:
        return stallList

    mg_client = get_mongo_client()
    try:
        for id in diningNo:
            cond = {'diningNo': id}
            res = mg_client[dbSynPosDining][collectionDiningList].find_one(cond)
            if res is None:
                return False
            tempres = res.get('stallList')
            if tempres is None:
                return stallList 

            for v in tempres:
                if RelationStallNo == v.get('stallNo'):
                    users = {
                        'diningNo': id,
                        'diningName': res['diningName'],
                        'stallNo': v.get('stallNo'),
                        'stallName': v.get('stallName'),
                        'createTime': globalTimeToString(v.get('createTime')),
                        'updateTime': globalTimeToString(v.get('updateTime')),
                        'creatorUserName': v.get('creatorUserName'),
                        'editorUserName': v.get('editorUserName'),
                        'stallDesc': v.get('stallDesc')
                    }
                    stallList.append(users)

        return stallList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryStallName(id):
    '''
    查询档口名
    '''
    mg_client = get_mongo_client()
    try:
        res = mg_client[dbSynPosDining][collectionDiningList].find()
        for v in res:
            tempres = v.get('stallList')
            if tempres is not None:
                for r in tempres:
                    if r.get('stallNo') == id:
                        return r.get('stallName')
        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryPos(diningNo, stallNo):
    '''
    查询点餐机
    '''
    try:
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosDining][collectionStallDeviceList].find_one(cond)
        if res is None:
            return False

        deviceList = []
        tempres = res.get('deviceList')
        if tempres is None:
            return deviceList

        for v in tempres:
            device = {
                'diningNo': diningNo,
                'diningName': queryDiningName(diningNo),
                'stallNo': stallNo,
                'stallName': queryStallName(stallNo),
                'deviceNo': v.get('deviceNo'),
                'softVersion': v.get('softVersion'),
                'deviceType': v.get('deviceType'),
                'skj130No': v.get('skj130No'),
                'updateTime': v.get('updateTime'),
                'upgradeState': v.get('upgradeState')
            }
            deviceList.append(device)   

        return deviceList
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getUpgradeState(diningNo, stallNo, deviceNo):
    '''
    获取设备升级状态
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionStallDeviceList]
        cond = {'diningNo': diningNo, 'stallNo': stallNo}
        res = collection.find_one(cond)
        # 如果该餐厅不存在
        if res is None:
            return None

        newList = res.get('deviceList')
        if newList is None or len(newList) <= 0:
            return None

        # 如果该设备存在
        for v in newList:
            deviceNo_str = v.get('deviceNo')
            if deviceNo_str == deviceNo:
                return v.get('upgradeState')

        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryStallIds(diningNo):
    '''
    查询指定餐厅的所有档口Id
    '''
    try:
        cond = {'diningNo': diningNo}
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosDining][collectionDiningList].find_one(cond)
        if res is None:
            return False

        IdList = []
        tempres = res.get('stallList')
        if tempres is None:
            return IdList

        for v in tempres:
            IdList.append(v.get('stallNo'))   

        return IdList
    except Exception as e:
        raise ErrMongoClient.data(str(e))
    

def nameSearch(diningNo, stallName):
    '''
    餐厅档口模糊搜索
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosDining][collectionDiningList]
        cond = {'diningNo': diningNo}
        res = collection.find_one(cond)
        # 如果该餐厅不存在
        if res is None:
            return None

        stallList = res.get('stallList')
        if stallList is None or len(stallList) <= 0:
            return None
        
        res_stallList = []
        for v in stallList:
            stallInfo = {
                "diningNo": res.get('diningNo'),
                "diningName": res.get('diningName'),
                "stallNo": v.get('stallNo'),
                "stallName": v.get('stallName'),
                "createTime": globalTimeToString(v.get('createTime')),
                "updateTime": globalTimeToString(v.get('updateTime')),
                "creatorUserName": v.get('creatorUserName'),
                "editorUserName": v.get('editorUserName'),
                "stallDesc": v.get('stallDesc')
            }
            res_stallList.append(stallInfo)

        res_stallList_ult = []
        if len(stallName) > 0:
            for v in res_stallList:
                if stallName in v.get('stallName'):
                    res_stallList_ult.append(v)
        else:
            res_stallList_ult = res_stallList
                      
        return res_stallList_ult
    except Exception as e:
        raise ErrMongoClient.data(str(e))